﻿using AutoMapper;
using FluentAssertions;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NewRetail.Application.Components.Platform;
using NewRetail.Application.Components.Platform.Entity;
using NewRetail.Application.Components.WeChat.CardVoucher.Model;
using NewRetail.Application.Components.WeChat.Configurations;
using NewRetail.Application.Components.WeChat.Member.Entity;
using NewRetail.Application.Components.WeChat.Member.Model;
using NewRetail.Application.Components.WeChat.Services;
using NewRetail.Application.Components.WeChat.Services.HttpClients;
using NewRetail.Application.Components.WeChat.TemplateMessage.Model;
using NewRetail.Application.Components.WeChat.TemplateMessage.Services;
using NewRetail.Application.Core.Entity;
using NewRetail.Application.Utility;
using SKIT.FlurlHttpClient.Wechat.Api;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Uow;

namespace NewRetail.Application.Components.WeChat.Member.Services
{
    #region 微信会员服务接口
    /// <summary>
    /// 微信会员服务接口
    /// </summary>
    public interface IMemberService : IApplicationService
    {
        /// <summary>
        /// 根据openId获取用户信息（SKIT.FlurlHttpClient）
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="appId"></param>
        /// <returns></returns>
        Task<WeChatMember> GetUserInfoByOpenId(string openId, string appId);
        /// <summary>
        /// 根据openId获取本地数据库用户信息
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        Task<PosMember> GetLocalUserInfoByOpenId(string openId);
        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="nextOpenId"></param>
        /// <returns></returns>
        Task<WeChatUserListDto> GetUserList(string appId, string nextOpenId = null);
        /// <summary>
        /// 根据获取的openId校验会员是否存在，不存在则加入
        /// </summary>
        /// <param name="weChatMemberVerAdd"></param>
        /// <param name="verType"></param>
        /// <returns></returns>
        Task<bool> VerifyMemberAdd(WeChatMemberVerAdd weChatMemberVerAdd, string verType = "GZ");
        /// <summary>
        /// 根据类型发送模板消息
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="openId"></param>
        /// <param name="templateMsgType">0:关注发送  1:购物成功发送</param>
        /// <returns></returns>
        Task SendTemplateMessageByType(string appId, string openId, int templateMsgType = 0);
        /// <summary>
        /// 创建会员卡
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        Task<(string, string)> CreateWeChatCardAsync(WeChatCardCreateInputDto inputData);
        /// <summary>
        /// 批量查询卡券列表
        /// </summary>
        /// <param name="inputDate"></param>
        /// <returns></returns>
        Task<(CardBatchGetResponse, string)> QueryWeChatCardListAsync(WeChatCardListQueryInputDto inputDate);
        /// <summary>
        /// 查看卡券详情
        /// </summary>
        /// <param name="cardId"></param>
        /// <param name="appId"></param>
        /// <returns></returns>
        Task<(CardGetResponse, string)> QueryWeChatCardDetailAsync(string cardId, string appId);
        /// <summary>
        /// 删除卡券
        /// </summary>
        /// <param name="inputDate"></param>
        /// <returns></returns>
        Task<(CardDeleteResponse, string)> DeleteWeChatCardAsync(WeChatCardDeleteInputDto inputDate);
        /// <summary>
        /// 创建卡券二维码
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        Task<(CardQrcodeCreateResponse, string)> CreateWeChatCardQrCodeAsync(CardQrcodeCreateInputDto inputData);
        /// <summary>
        /// 获取开卡插件参数 调用此接口后返回的url可以直接打开到领取卡界面
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        Task<(CardMemberCardActivateGetUrlResponse, string)> GetCardMemberCardActivateAsync(CardMemberCardActivateInputDto inputData);
        /// <summary>
        /// 设置测试白名单
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        Task<(CardTestWhiteListSetResponse, string)> SetCardMemberTestWhiteListAsync(CardMemberTestWhiteListInputDto inputData);
        /// <summary>
        /// 拉取会员信息（积分查询）
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        Task<(CardMemberCardUserInfoGetResponse, string)> GetCardMemberUserInfoAsync(CardMemberUserInfoInputDto inputData);
        /// <summary>
        /// 解码code
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        Task<(CardCodeDecryptResponse, string)> CardMemberDecryptCodeAsync(CardMemberDecryptCodeInputDto inputData);
        /// <summary>
        /// 查询code
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        Task<(CardCodeGetResponse, string)> CardMemberQueryCodeAsync(CardMemberQueryCodeInputDto inputData);
        /// <summary>
        /// 检查是否已存在线上会员
        /// </summary>
        /// <param name="openId"></param>
        /// <returns>true:存在  false:不存在</returns>
        Task<bool> IsExistsMemberByOpenId(string openId);
        /// <summary>
        /// 获取用户已领取卡券
        /// </summary>
        /// <param name="inputDate"></param>
        /// <returns></returns>
        Task<(CardUserGetCardListResponse, string)> CardUserGetCardListAsync(WeChatCardUserCardInputDto inputDto);
        /// <summary>
        /// 更新会员信息(积分信息)
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        Task<(CardMemberCardUpdateUserResponse, string)> UpdateWeChatUserMemberCardAsync(UpdateWeChatUserMemberCardInputDto inputDto, CancellationToken cancellationToken = default(CancellationToken));
    }
    #endregion

    #region 微信会员服务接口的实现
    /// <summary>
    /// 微信会员服务接口的实现
    /// </summary>
    public class MemberService : ApplicationService, IMemberService
    {
        #region Field
        private readonly ILogger _logger;
        private readonly IHttpContextAccessor _accessor;
        //private readonly RedisClient _redisClient;
        private readonly IWeChatApiHttpClientFactory _wechatApiHttpClientFactory;
        private readonly IMapper _mapper;
        public readonly ITemplateMessageService _templateMessageService;
        private readonly WeChatOptions _wechatOptions;
        private readonly IWeChatAccessToken _weChatAccessToken;

        private readonly IUnitOfWorkManager _unitOfWorkManager;

        private readonly IRepository<PosMember> _posMemberRepository;
        protected IEntityHelper _entityHelper => this.LazyServiceProvider.LazyGetRequiredService<IEntityHelper>();
        protected INoGeneratorService _noGeneratorService => this.LazyServiceProvider.LazyGetRequiredService<INoGeneratorService>();

        #endregion

        #region Constructor
        public MemberService(IHttpContextAccessor accessor, IWeChatApiHttpClientFactory wechatApiHttpClientFactory, IWeChatAccessToken weChatAccessToken,
            ITemplateMessageService templateMessageService, IOptions<WeChatOptions> wechatOptions, IRepository<PosMember> posMemberRepository,
            IUnitOfWorkManager unitOfWorkManager, IMapper mapper, ILogger<MemberService> logger)
        {
            _accessor = accessor;
            _weChatAccessToken = weChatAccessToken;
            _wechatApiHttpClientFactory = wechatApiHttpClientFactory;
            _templateMessageService = templateMessageService;
            _posMemberRepository = posMemberRepository;
            _wechatOptions = wechatOptions.Value;
            _unitOfWorkManager = unitOfWorkManager;
            _mapper = mapper;
            _logger = logger;
        }
        #endregion

        #region method        

        #region 根据openId获取微信用户信息
        /// <summary>
        /// 根据openId获取微信用户信息（SKIT.FlurlHttpClient）
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="appId"></param>
        /// <returns></returns>
        public async Task<WeChatMember> GetUserInfoByOpenId(string openId, string appId)
        {
            var resultUserInfo = await GetWeChatUserInfoByOpenId(openId, appId);
            
            return resultUserInfo;
        }
        #endregion

        #region 根据openId获取本地数据库用户信息
        /// <summary>
        /// 根据openId获取本地数据库用户信息
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        public async Task<PosMember> GetLocalUserInfoByOpenId(string openId)
        {
            var db = await _posMemberRepository.GetDbContextAsync();
            //根据openId获取会员
            var posMember = await db.Set<PosMember>().AsNoTracking().FirstOrDefaultAsync(x => x.openId == openId);

            return posMember;
        }
        #endregion

        #region 获取用户列表
        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="nextOpenId"></param>
        /// <returns></returns>
        public async Task<WeChatUserListDto> GetUserList(string appId, string nextOpenId = null)
        {
            //获取accessToken对象
            var wechatAccessToken = await _weChatAccessToken.GetAccessTokenObject(appId);
            //创建一个http
            var wechatApiclient = _wechatApiHttpClientFactory.Create(appId);
            //请求参数
            var requestData = new CgibinUserGetRequest() { AccessToken = wechatAccessToken?.AccessToken, NextOpenId = nextOpenId };
            //请求获取数据
            var userListResponse = await wechatApiclient.ExecuteCgibinUserGetAsync(requestData, cancellationToken: _accessor.HttpContext.RequestAborted);
            if (!userListResponse.IsSuccessful())
            {
                _logger.LogWarning(
                    "获取用户列表失败（状态码：{0}，错误代码：{1}，错误描述：{2}）。",
                    userListResponse.RawStatus, userListResponse.ErrorCode, userListResponse.ErrorMessage
                );
            }
            var resultUserList = _mapper.Map<WeChatUserListDto>(userListResponse);
            resultUserList.OpenIdData = new WeChatUserListDto.Types.Data() { OpenIdList = userListResponse.Data?.OpenIdList };
            return resultUserList;
        }
        #endregion

        #region 根据获取的openId校验会员是否存在，不存在则加入
        /// <summary>
        /// 根据获取的openId校验会员是否存在，不存在则加入
        /// </summary>
        /// <param name="weChatMemberVerAdd"></param>
        /// <param name="verType"></param>
        /// <returns></returns>
        public async Task<bool> VerifyMemberAdd(WeChatMemberVerAdd weChatMemberVerAdd, string verType = "GZ")
        {
            var result = false;
            weChatMemberVerAdd.Should().NotBeNull();
            var openId = weChatMemberVerAdd.openId;
            
            //openId为空直接返回null
            if (string.IsNullOrEmpty(openId))
                return false;
            //插入会员
            result = await InsertPosMemberAsync(weChatMemberVerAdd);

            return result;

            //var db = await _posMemberRepository.GetDbContextAsync();
            //var posMember = await db.Set<PosMember>().AsNoTracking().FirstOrDefaultAsync(x => x.openId == openId); 
            ////关注
            //if (verType =="GZ")
            //{
            //    if (posMember == null)
            //    {
            //        //会员不存在则需要新增，且根据手机号判断记录
            //        posMember = await InsertPosMemberAsync(appId, sourceWarehouseID, memberName, openId, memberTypeID, memberTel);
            //        //posMember = new PosMember()
            //        //{
            //        //    sourceWarehouseID = sourceWarehouseID,
            //        //    startDate = DateTime.Now,
            //        //    endDate = DateTime.Now.AddYears(10),
            //        //    memberName = memberName,
            //        //    cardAmount = 0,
            //        //    TotalConsAmount = 0,
            //        //    integral = 0,
            //        //    openId = openId
            //        //};
            //        ////添加卡号
            //        //posMember.No = await _noGeneratorService.GenerateGeneralNoAsync("MB");
            //        //posMember.memberTypeID = memberTypeID;
            //        ////获取微信用户详情
            //        //var weChatMember = await GetWeChatUserInfoByOpenId(openId, appId);
            //        //posMember.memberName = weChatMember.Nickname;
            //        //_entityHelper.InitEntity(posMember);
            //        //await _posMemberRepository.InsertAsync(posMember, autoSave: true);

            //        ////var result = new ResponseEntity<PosMember>().SetData(weChatMember).SetSuccess();
            //    }
            //}
            ////领卡激活
            //else if (verType == "LKJH")
            //{     
            //    //关注后领取激活的
            //    if (posMember != null && !string.IsNullOrEmpty(memberTel))
            //    {
            //        var posTelMember = await db.Set<PosMember>().AsNoTracking().FirstOrDefaultAsync(x => x.memberTel == memberTel && string.IsNullOrEmpty(x.openId));
            //        if (posTelMember != null)
            //        {
            //            //手机号已经存在并且对应记录的openId为空，则需要合并记录。
            //            using var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true);
            //            try
            //            {
            //                //更新存在的手机号记录的openId
            //                posTelMember.openId = openId;
            //                posTelMember.updateTime = DateTime.Now;
            //                _entityHelper.SetUpdationInfo(posTelMember);
            //                await _posMemberRepository.UpdateAsync(posTelMember);
            //                //删除openId存在，手机号不存在的记录
            //                await _posMemberRepository.DeleteAsync(posMember);

            //                await uow.CompleteAsync();
            //            }
            //            catch(Exception e)
            //            {
            //                await uow.RollbackAsync();
            //                _logger.LogError(message: e.Message, exception: e);
            //                throw;
            //            }
            //        }
            //        else
            //        {
            //            //手机号不存在则更新对应的openId的memberTel                        
            //            posMember.memberTel = memberTel;
            //            //会员号也设置为手机号
            //            posMember.No = memberTel;
            //            posMember.updateTime = DateTime.Now;
            //            _entityHelper.SetUpdationInfo(posMember);
            //            await _posMemberRepository.UpdateAsync(posMember, autoSave: true);
            //        }                                       
            //    }
            //    else if (posMember == null)
            //    {
            //        //如果对应此用户openId不存在，即没关注领的卡，那么直接插入会员数据
            //        posMember = await InsertPosMemberAsync(appId, sourceWarehouseID, memberName, openId, memberTypeID, memberTel);
            //    }
            //}
            //return posMember;
        }
        #endregion

        #region 根据类型发送模板消息
        /// <summary>
        /// 根据类型发送模板消息
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="openId"></param>
        /// <param name="templateMsgType">0:关注发送  1:购物成功发送</param>
        /// <returns></returns>
        public async Task SendTemplateMessageByType(string appId, string openId, int templateMsgType = 0)
        {
            var templateId = "";
            //如果appId为空，那么就直接获取默认第一个
            if (string.IsNullOrEmpty(appId))
                appId = _wechatOptions.Accounts?.FirstOrDefault().AppId;

            var messageData = new Dictionary<string, CgibinMessageTemplateSendRequest.Types.DataItem>();
            if (templateMsgType == 0)
            {
                templateId = _wechatOptions.Accounts?.FirstOrDefault(e => string.Equals(appId, e.AppId)).TemplateSendInfo.AttentionTemplateId;

                messageData.Add("first", new CgibinMessageTemplateSendRequest.Types.DataItem() { Value = "您好，欢迎关注", Color = "#173177" });
                messageData.Add("keyword1", new CgibinMessageTemplateSendRequest.Types.DataItem() { Value = "优惠" });
                messageData.Add("keyword2", new CgibinMessageTemplateSendRequest.Types.DataItem() { Value = "77" });
                messageData.Add("remark", new CgibinMessageTemplateSendRequest.Types.DataItem() { Value = "如有疑问，请致电xxxxx联系我们，或回复M来了解详情" });
            }
            var templateMsgSendData = new TemplateMsgSendDto()
            {
                AppId = appId,
                MessageType = templateMsgType,
                OpenId = openId,
                TemplateId = templateId,
                MessageItemDate = messageData
            };
            var result = await _templateMessageService.Send(templateMsgSendData);
        }
        #endregion

        #region 会员卡相关

        #region 创建会员卡
        /// <summary>
        /// 创建会员卡
        /// </summary>
        /// <returns></returns>
        public async Task<(string, string)> CreateWeChatCardAsync(WeChatCardCreateInputDto inputData)
        {
            var cardId = "";
            var appId = inputData.AppId;
            //获取accessToken对象
            var wechatAccessToken = await _weChatAccessToken.GetAccessTokenObject(appId);
            //创建一个http
            var wechatApiclient = _wechatApiHttpClientFactory.Create(appId);

            var textImageList = new List<CardCreateRequest.Types.GrouponCard.Types.Advance.Types.TextImage>();
            foreach(var item in inputData.AdvanceInfo.TextImageList)
            {
                textImageList.Add(new CardCreateRequest.Types.GrouponCard.Types.Advance.Types.TextImage() { ImageUrl = item.ImageUrl, Text = item.Text });
            }
            var timeLimitList = new List<CardCreateRequest.Types.GrouponCard.Types.Advance.Types.TimeLimit>();
            if (inputData.AdvanceInfo.TimeLimitList != null)
            {
                foreach (var item in inputData.AdvanceInfo.TimeLimitList)
                {
                    timeLimitList.Add(new CardCreateRequest.Types.GrouponCard.Types.Advance.Types.TimeLimit() { Type = item.Type, BeginHour = item.BeginHour, EndHour = item.EndHour, BeginMinute = item.BeginMinute, EndMinute = item.EndMinute });
                }
            }

            var requestData = new CardCreateRequest()
            {
                AccessToken = wechatAccessToken?.AccessToken,
                Card = new CardCreateRequest.Types.Card() 
                {
                    CardType = inputData.CardType,
                    Membership=new CardCreateRequest.Types.MembershipCard()
                    {
                        Base=new CardCreateRequest.Types.MembershipCard.Types.Base()
                        {
                            LogoUrl = inputData.Base.LogoUrl,
                            BrandName=inputData.Base.BrandName,
                            CodeType=inputData.Base.CodeType,
                            Title=inputData.Base.Title,
                            Color=inputData.Base.Color,
                            Notice=inputData.Base.Notice,
                            ServicePhoneNumber=inputData.Base.ServicePhoneNumber,
                            Description=inputData.Base.Description,
                            Date=new CardCreateRequest.Types.GrouponCard.Types.Base.Types.Date()
                            {
                                Type= inputData.Base.DateInfo.Type
                            },
                            SKU=new CardCreateRequest.Types.GrouponCard.Types.Base.Types.SKU()
                            {
                                Quantity=inputData.Base.Sku.Quantity
                            },
                            GetLimitPerUser=inputData.Base.GetLimitPerUser,
                            UseCustomCode =inputData.Base.UseCustomCode,
                            CanTransfer=inputData.Base.CanGiveFriend,
                            CustomUrl =inputData.Base.CustomUrl,
                            CustomUrlTitle=inputData.Base.CustomUrlTitle,
                            RequirePushOnView = inputData.Base.NeedPushOnView                           
                        },
                        Advance=new CardCreateRequest.Types.MembershipCard.Types.Advance()
                        {
                            UseCondition=new CardCreateRequest.Types.GrouponCard.Types.Advance.Types.UseCondition()
                            {
                                AcceptCategory=inputData.AdvanceInfo.UseCondition.AcceptCategory,
                                RejectCategory = inputData.AdvanceInfo.UseCondition.RejectCategory,
                                CanUseWithOtherDiscount= inputData.AdvanceInfo.UseCondition.CanUseWithOtherDiscount
                            },
                            Abstract=new CardCreateRequest.Types.GrouponCard.Types.Advance.Types.Abstract()
                            {
                                Description= inputData.AdvanceInfo.Abstract.Description,
                                IconUrlList= inputData.AdvanceInfo.Abstract.IconUrlList
                            },
                            TextImageList= textImageList,
                            TimeLimitList= timeLimitList,
                            BusinessServiceList= inputData.AdvanceInfo.BusinessServiceList,
                        },
                        IsSupplyBalance=inputData.IsSupplyBalance,
                        IsSupplyBonus=inputData.IsSupplyBonus,
                        Prerogative=inputData.Prerogative,
                        IsAutoActivate=inputData.IsAutoActivate,
                        IsWechatActivate=inputData.IsWechatActivate,
                        CustomField1=new CardCreateRequest.Types.MembershipCard.Types.CustomField()
                        {
                            NameType= inputData.CustomField1.NameType,
                            Name= inputData.CustomField1.Name
                        },
                        ActivateUrl=inputData.ActivateUrl,
                        CustomCell1=new CardCreateRequest.Types.MembershipCard.Types.CustomCell()
                        {
                            Name= inputData.CustomCell1.Name,
                            Tips = inputData.CustomCell1.Tips,
                            Url = inputData.CustomCell1.Url
                        },
                        BonusRule=new CardCreateRequest.Types.MembershipCard.Types.BonusRule()
                        {
                            CostBonusUnit= inputData.BonusRule.CostBonusUnit,
                            CostMoneyUnit= inputData.BonusRule.CostMoneyUnit,
                            IncreaseBonus= inputData.BonusRule.IncreaseBonus,
                            MaxIncreaseBonus= inputData.BonusRule.MaxIncreaseBonus,
                            InitialIncreaseBonus= inputData.BonusRule.InitialIncreaseBonus,
                            ReduceMoney= inputData.BonusRule.ReduceMoney,
                            LeastMoneyToUseBonus= inputData.BonusRule.LeastMoneyToUseBonus,
                            MaxReduceBonus= inputData.BonusRule.MaxReduceBonus
                        },
                        Discount=inputData.Discount
                    }
                }
                
            };

            var responseInfo = await wechatApiclient.ExecuteCardCreateAsync(requestData, cancellationToken: _accessor.HttpContext.RequestAborted);
            if (!responseInfo.IsSuccessful())
            {
                _logger.LogWarning(
                    "创建会员卡失败（状态码：{0}，错误代码：{1}，错误描述：{2}）。",
                    responseInfo.RawStatus, responseInfo.ErrorCode, responseInfo.ErrorMessage
                );
            }
            else
            {
                cardId = responseInfo.CardId;
                //创建成功则插入数据库
                //var db = await _cardVoucherRepository.GetDbContextAsync();
                //var cardVoucher = await db.Set<CardVoucherInfo>().AsNoTracking().FirstOrDefaultAsync(x => x.stockId == stockId);
                //if (cardVoucher == null)
                //{
                //    //如果批次号不存在则插入
                //    cardVoucher = new CardVoucherInfo()
                //    {
                //        stockId = stockId,
                //        stockName = inputData.StockName,
                //        stockType = inputData.StockType,
                //        availableBeginTime = inputData.AvailableBeginTime.ToString("yyyy-MM-ddTHH:mm:ssK"),
                //        availableEndTime = inputData.AvailableEndTime.ToString("yyyy-MM-ddTHH:mm:ssK"),
                //        outRequestNo = outRequestNo,
                //        noCash = inputData.IsNoCash,
                //        maxCoupons = inputData.MaxCoupons,
                //        maxAmount = inputData.MaxAmount,
                //        maxAmountByDay = inputData.MaxAmountPerDay,
                //        maxCouponsPerUser = inputData.MaxCouponsPerUser,
                //        naturalPersonLimit = inputData.IsNaturalPersonLimit,
                //        preventApiAbuse = inputData.IsPreventApiAbuse,
                //        isActive = false
                //    };
                //    _entityHelper.InitEntity(cardVoucher);
                //    await _cardVoucherRepository.InsertAsync(cardVoucher, autoSave: true);
                //}
            }


            return (cardId, responseInfo.ErrorMessage);
        }
        #endregion

        #region 批量查询卡券列表
        /// <summary>
        /// 批量查询卡券列表
        /// </summary>
        /// <param name="inputDate"></param>
        /// <returns></returns>
        public async Task<(CardBatchGetResponse, string)> QueryWeChatCardListAsync(WeChatCardListQueryInputDto inputDate)
        {
            //获取accessToken对象
            var wechatAccessToken = await _weChatAccessToken.GetAccessTokenObject(inputDate.AppId);
            //创建一个http
            var wechatApiclient = _wechatApiHttpClientFactory.Create(inputDate.AppId);

            var requestData = new CardBatchGetRequest()
            {
                AccessToken = wechatAccessToken?.AccessToken,
                Offset = inputDate.Offset,
                Limit=inputDate.Limit,
                StatusList=inputDate.StatusList
            };

            var responseInfo = await wechatApiclient.ExecuteCardBatchGetAsync(requestData, cancellationToken: _accessor.HttpContext.RequestAborted);
            if (!responseInfo.IsSuccessful())
            {
                _logger.LogWarning(
                    "批量查询卡券列表失败（状态码：{0}，错误代码：{1}，错误描述：{2}）。",
                    responseInfo.RawStatus, responseInfo.ErrorCode, responseInfo.ErrorMessage
                );
            }

            return (responseInfo, responseInfo.ErrorMessage);
        }
        #endregion

        #region 查看卡券详情
        /// <summary>
        /// 查看卡券详情
        /// </summary>
        /// <param name="cardId"></param>
        /// <param name="appId"></param>
        /// <returns></returns>
        public async Task<(CardGetResponse, string)> QueryWeChatCardDetailAsync(string cardId, string appId)
        {
            //获取accessToken对象
            var wechatAccessToken = await _weChatAccessToken.GetAccessTokenObject(appId);
            //创建一个http
            var wechatApiclient = _wechatApiHttpClientFactory.Create(appId);

            var requestData = new CardGetRequest()
            {
                AccessToken = wechatAccessToken?.AccessToken,
                CardId = cardId
            };

            var responseInfo = await wechatApiclient.ExecuteCardGetAsync(requestData, cancellationToken: _accessor.HttpContext.RequestAborted);
            if (!responseInfo.IsSuccessful())
            {
                _logger.LogWarning(
                    "查看卡券详情失败（状态码：{0}，错误代码：{1}，错误描述：{2}）。",
                    responseInfo.RawStatus, responseInfo.ErrorCode, responseInfo.ErrorMessage
                );
            }

            return (responseInfo, responseInfo.ErrorMessage);
        }
        #endregion

        #region 删除卡券
        /// <summary>
        /// 删除卡券
        /// </summary>
        /// <param name="inputDate"></param>
        /// <returns></returns>
        public async Task<(CardDeleteResponse, string)> DeleteWeChatCardAsync(WeChatCardDeleteInputDto inputDate)
        {
            //获取accessToken对象
            var wechatAccessToken = await _weChatAccessToken.GetAccessTokenObject(inputDate.AppId);
            //创建一个http
            var wechatApiclient = _wechatApiHttpClientFactory.Create(inputDate.AppId);

            var requestData = new CardDeleteRequest()
            {
                AccessToken = wechatAccessToken?.AccessToken,
                CardId = inputDate.CardId
            };

            var responseInfo = await wechatApiclient.ExecuteCardDeleteAsync(requestData, cancellationToken: _accessor.HttpContext.RequestAborted);
            if (!responseInfo.IsSuccessful())
            {
                _logger.LogWarning(
                    "删除卡券失败（状态码：{0}，错误代码：{1}，错误描述：{2}）。",
                    responseInfo.RawStatus, responseInfo.ErrorCode, responseInfo.ErrorMessage
                );
            }

            return (responseInfo, responseInfo.ErrorMessage);
        }
        #endregion

        #region 创建卡券二维码
        /// <summary>
        /// 创建卡券二维码
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public async Task<(CardQrcodeCreateResponse, string)> CreateWeChatCardQrCodeAsync(CardQrcodeCreateInputDto inputData)
        {
            //获取accessToken对象
            var wechatAccessToken = await _weChatAccessToken.GetAccessTokenObject(inputData.AppId);
            //创建一个http
            var wechatApiclient = _wechatApiHttpClientFactory.Create(inputData.AppId);

            var requestData = new CardQrcodeCreateRequest()
            {
                AccessToken = wechatAccessToken?.AccessToken,
                ExpiresIn=inputData.ExpiresIn,
                ActionType=inputData.ActionName,
                Action = new CardQrcodeCreateRequest.Types.Action()
                {
                    Card=new CardQrcodeCreateRequest.Types.Action.Types.Card()
                    {
                        CardCode= inputData.Action.Card.CardCode,
                        CardId= inputData.Action.Card.CardId,
                        OpenId= inputData.Action.Card.OpenId,
                        IsUnique= inputData.Action.Card.IsUnique,
                        OuterString= inputData.Action.Card.OuterString
                    }
                }
            };

            var responseInfo = await wechatApiclient.ExecuteCardQrcodeCreateAsync(requestData, cancellationToken: _accessor.HttpContext.RequestAborted);
            if (!responseInfo.IsSuccessful())
            {
                _logger.LogWarning(
                    "创建卡券二维码失败（状态码：{0}，错误代码：{1}，错误描述：{2}）。",
                    responseInfo.RawStatus, responseInfo.ErrorCode, responseInfo.ErrorMessage
                );
            }

            return (responseInfo, responseInfo.ErrorMessage);
        }
        #endregion

        #region 获取开卡插件参数
        /// <summary>
        /// 获取开卡插件参数
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public async Task<(CardMemberCardActivateGetUrlResponse, string)> GetCardMemberCardActivateAsync(CardMemberCardActivateInputDto inputData)
        {
            //获取accessToken对象
            var wechatAccessToken = await _weChatAccessToken.GetAccessTokenObject(inputData.AppId);
            //创建一个http
            var wechatApiclient = _wechatApiHttpClientFactory.Create(inputData.AppId);

            var requestData = new CardMemberCardActivateGetUrlRequest()
            {
                AccessToken = wechatAccessToken?.AccessToken,
                CardId = inputData.CardId,
                OuterString = inputData.OuterString
            };

            var responseInfo = await wechatApiclient.ExecuteCardMemberCardActivateGetUrlAsync(requestData, cancellationToken: _accessor.HttpContext.RequestAborted);
            if (!responseInfo.IsSuccessful())
            {
                _logger.LogWarning(
                    "创建卡券二维码失败（状态码：{0}，错误代码：{1}，错误描述：{2}）。",
                    responseInfo.RawStatus, responseInfo.ErrorCode, responseInfo.ErrorMessage
                );
            }

            return (responseInfo, responseInfo.ErrorMessage);
        }
        #endregion

        #region 设置测试白名单
        /// <summary>
        /// 设置测试白名单
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public async Task<(CardTestWhiteListSetResponse, string)> SetCardMemberTestWhiteListAsync(CardMemberTestWhiteListInputDto inputData)
        {
            //获取accessToken对象
            var wechatAccessToken = await _weChatAccessToken.GetAccessTokenObject(inputData.AppId);
            //创建一个http
            var wechatApiclient = _wechatApiHttpClientFactory.Create(inputData.AppId);

            var requestData = new CardTestWhiteListSetRequest()
            {
                AccessToken = wechatAccessToken?.AccessToken,
                OpenIdList = inputData.OpenIdList
            };

            var responseInfo = await wechatApiclient.ExecuteCardTestWhiteListSetAsync(requestData, cancellationToken: _accessor.HttpContext.RequestAborted);
            if (!responseInfo.IsSuccessful())
            {
                _logger.LogWarning(
                    "设置测试白名单失败（状态码：{0}，错误代码：{1}，错误描述：{2}）。",
                    responseInfo.RawStatus, responseInfo.ErrorCode, responseInfo.ErrorMessage
                );
            }

            return (responseInfo, responseInfo.ErrorMessage);
        }
        #endregion

        #region 拉取会员信息（积分查询）
        /// <summary>
        /// 拉取会员信息（积分查询）
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public async Task<(CardMemberCardUserInfoGetResponse, string)> GetCardMemberUserInfoAsync(CardMemberUserInfoInputDto inputData)
        {
            string appId = inputData.AppId;
            //appid不指定，那么获取配置第一个
            if (string.IsNullOrEmpty(appId))
                appId = _wechatOptions.Accounts?.FirstOrDefault().AppId;
            //获取accessToken对象
            var wechatAccessToken = await _weChatAccessToken.GetAccessTokenObject(appId);
            //创建一个http
            var wechatApiclient = _wechatApiHttpClientFactory.Create(appId);

            var requestData = new CardMemberCardUserInfoGetRequest()
            {
                AccessToken = wechatAccessToken?.AccessToken,
                CardId = inputData.CardId,
                CardCode= inputData.CardCode
            };

            var responseInfo = await wechatApiclient.ExecuteCardMemberCardUserInfoGetAsync(requestData, cancellationToken: _accessor.HttpContext.RequestAborted);
            if (!responseInfo.IsSuccessful())
            {
                _logger.LogWarning(
                    "拉取会员信息（积分查询）失败（状态码：{0}，错误代码：{1}，错误描述：{2}）。",
                    responseInfo.RawStatus, responseInfo.ErrorCode, responseInfo.ErrorMessage
                );
            }

            return (responseInfo, responseInfo.ErrorMessage);
        }
        #endregion

        #region 解码code
        /// <summary>
        /// 解码code
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public async Task<(CardCodeDecryptResponse, string)> CardMemberDecryptCodeAsync(CardMemberDecryptCodeInputDto inputData)
        {
            //获取accessToken对象
            var wechatAccessToken = await _weChatAccessToken.GetAccessTokenObject(inputData.AppId);
            //创建一个http
            var wechatApiclient = _wechatApiHttpClientFactory.Create(inputData.AppId);

            var requestData = new CardCodeDecryptRequest()
            {
                AccessToken = wechatAccessToken?.AccessToken,
                EncryptedCardCode = inputData.EncryptedCardCode
            };

            var responseInfo = await wechatApiclient.ExecuteCardCodeDecryptAsync(requestData, cancellationToken: _accessor.HttpContext.RequestAborted);
            if (!responseInfo.IsSuccessful())
            {
                _logger.LogWarning(
                    "解码code失败（状态码：{0}，错误代码：{1}，错误描述：{2}）。",
                    responseInfo.RawStatus, responseInfo.ErrorCode, responseInfo.ErrorMessage
                );
            }

            return (responseInfo, responseInfo.ErrorMessage);
        }
        #endregion

        #region 查询code
        /// <summary>
        /// 查询code
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public async Task<(CardCodeGetResponse, string)> CardMemberQueryCodeAsync(CardMemberQueryCodeInputDto inputData)
        {
            //获取accessToken对象
            var wechatAccessToken = await _weChatAccessToken.GetAccessTokenObject(inputData.AppId);
            //创建一个http
            var wechatApiclient = _wechatApiHttpClientFactory.Create(inputData.AppId);

            var requestData = new CardCodeGetRequest()
            {
                AccessToken = wechatAccessToken?.AccessToken,
                CardId = inputData.CardId,
                CardCode = inputData.CardCode,
                RequireCheckConsume = inputData.RequireCheckConsume
            };

            var responseInfo = await wechatApiclient.ExecuteCardCodeGetAsync(requestData, cancellationToken: _accessor.HttpContext.RequestAborted);
            if (!responseInfo.IsSuccessful())
            {
                _logger.LogWarning(
                    "查询code失败（状态码：{0}，错误代码：{1}，错误描述：{2}）。",
                    responseInfo.RawStatus, responseInfo.ErrorCode, responseInfo.ErrorMessage
                );
            }

            return (responseInfo, responseInfo.ErrorMessage);
        }
        #endregion

        #region 检查是否已存在线上会员
        /// <summary>
        /// 检查是否已存在线上会员
        /// </summary>
        /// <param name="openId"></param>
        /// <returns>true:存在  false:不存在</returns>
        public async Task<bool> IsExistsMemberByOpenId(string openId)
        {
            var db = await _posMemberRepository.GetDbContextAsync();
            var posMember = await db.Set<PosMember>().AsNoTracking().FirstOrDefaultAsync(x => x.openId == openId);
            if (posMember == null)
                return false;
            else if(string.IsNullOrEmpty(posMember.memberTel))
                return false;
            else
                return true;
        }
        #endregion

        #region 获取用户已领取卡券
        /// <summary>
        /// 获取用户已领取卡券
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<(CardUserGetCardListResponse, string)> CardUserGetCardListAsync(WeChatCardUserCardInputDto inputDto)
        {
            string appId = inputDto.AppId;
            string memberCardId = inputDto.CardId;
            //appid不指定，那么获取配置第一个
            if (string.IsNullOrEmpty(appId))
                appId = _wechatOptions.Accounts?.FirstOrDefault().AppId;
            //CardId不指定，那么获取配置第一个
            if (string.IsNullOrEmpty(memberCardId))
                memberCardId = _wechatOptions.Accounts?.FirstOrDefault(e => string.Equals(appId, e.AppId)).MemberCardId;
            //获取accessToken对象
            var wechatAccessToken = await _weChatAccessToken.GetAccessTokenObject(appId);
            //创建一个http
            var wechatApiclient = _wechatApiHttpClientFactory.Create(appId);

            var requestData = new CardUserGetCardListRequest()
            {
                AccessToken = wechatAccessToken?.AccessToken,
                CardId = memberCardId,
                OpenId = inputDto.OpenId
            };

            var responseInfo = await wechatApiclient.ExecuteCardUserGetCardListAsync(requestData, cancellationToken: _accessor.HttpContext.RequestAborted);
            if (!responseInfo.IsSuccessful())
            {
                _logger.LogWarning(
                    "获取用户已领取卡券失败（状态码：{0}，错误代码：{1}，错误描述：{2}）。",
                    responseInfo.RawStatus, responseInfo.ErrorCode, responseInfo.ErrorMessage
                );
            }

            return (responseInfo, responseInfo.ErrorMessage);
        }
        #endregion

        #region 更新会员信息(积分信息)
        /// <summary>
        /// 更新会员信息(积分信息)
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<(CardMemberCardUpdateUserResponse, string)> UpdateWeChatUserMemberCardAsync(UpdateWeChatUserMemberCardInputDto inputDto, CancellationToken cancellationToken = default(CancellationToken))
        {
            string appId = inputDto.AppId;
            string memberCardId = inputDto.CardId;
            //appid不指定，那么获取配置第一个
            if (string.IsNullOrEmpty(appId))
                appId = _wechatOptions.Accounts?.FirstOrDefault().AppId;
            //CardId不指定，那么获取配置第一个
            if (string.IsNullOrEmpty(memberCardId))
                memberCardId = _wechatOptions.Accounts?.FirstOrDefault(e => string.Equals(appId, e.AppId)).MemberCardId;
            //获取accessToken对象
            var wechatAccessToken = await _weChatAccessToken.GetAccessTokenObject(appId);
            //创建一个http
            var wechatApiclient = _wechatApiHttpClientFactory.Create(appId);

            //根据openId获取cardCode
            var reqData = new CardUserGetCardListRequest()
            {
                AccessToken = wechatAccessToken?.AccessToken,
                CardId = memberCardId,
                OpenId = inputDto.OpenId
            };
            try
            {
                var resInfo = await wechatApiclient.ExecuteCardUserGetCardListAsync(reqData, cancellationToken: _accessor?.HttpContext?.RequestAborted ?? cancellationToken);
                if (!resInfo.IsSuccessful())
                {
                    _logger.LogWarning(
                        "获取用户已领取卡券失败（状态码：{0}，错误代码：{1}，错误描述：{2}）。",
                        resInfo.RawStatus, resInfo.ErrorCode, resInfo.ErrorMessage
                    );
                    return (null, "更新：" + resInfo.ErrorMessage);
                }
                else
                {

                    var cardCode = resInfo.CardList.FirstOrDefault(x => x.CardId == memberCardId).CardCode;

                    var requestData = new CardMemberCardUpdateUserRequest()
                    {
                        AccessToken = wechatAccessToken?.AccessToken,
                        CardId = memberCardId,
                        CardCode = cardCode,
                        Bounus = inputDto.Bounus,
                        ModifiedBounus = inputDto.ModifiedBounus,
                        ModifiedBounusRecord = inputDto.ModifiedBounusRecord
                    };

                    var responseInfo = await wechatApiclient.ExecuteCardMemberCardUpdateUserAsync(requestData, cancellationToken: _accessor?.HttpContext?.RequestAborted ?? cancellationToken);
                    if (!responseInfo.IsSuccessful())
                    {
                        _logger.LogWarning(
                            "更新会员信息失败（状态码：{0}，错误代码：{1}，错误描述：{2}）。",
                            responseInfo.RawStatus, responseInfo.ErrorCode, responseInfo.ErrorMessage
                        );
                    }
                    return (responseInfo, "");// responseInfo.ErrorMessage);
                }
            }
            catch(Exception e)
            {
                _logger.LogError("异常："+e.Message);
                return (null, "异常：" + e.Message);
            }
        }
        #endregion

        #endregion

        #endregion

        #region private method

        #region 根据openId获取用户信息
        /// <summary>
        /// 根据openId获取用户信息
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="appId"></param>
        /// <returns></returns>
        private async Task<WeChatMember> GetWeChatUserInfoByOpenId(string openId, string appId)
        {
            ////获取Redis
            //var redis = _redisClient.Connection.GetDatabase(2);
            //var keyWechat = $"{ConstOptions.KeyWechatRedisPrefix}{appId}";
            ////获取redis里面键对应的值
            //var keyWechatValue = await redis.StringGetAsync(keyWechat);
            ////转成对象
            //var wechatAccessToken = keyWechatValue.IsNullOrEmpty ? null : UtilsHelper.DeserializeObject<WechatAccessTokenEntity>(keyWechatValue.ToString());

            //获取accessToken对象
            var wechatAccessToken = await _weChatAccessToken.GetAccessTokenObject(appId);
            //创建一个http
            var wechatApiclient = _wechatApiHttpClientFactory.Create(appId);
            //请求参数
            var reqUserInfo = new CgibinUserInfoRequest() { AccessToken = wechatAccessToken?.AccessToken, OpenId = openId };
            //请求获取数据
            var userInfoResponse = await wechatApiclient.ExecuteCgibinUserInfoAsync(reqUserInfo, cancellationToken: _accessor.HttpContext.RequestAborted);
            if (!userInfoResponse.IsSuccessful())
            {
                _logger.LogWarning(
                    "获取用户基本信息失败（状态码：{0}，错误代码：{1}，错误描述：{2}）。",
                    userInfoResponse.RawStatus, userInfoResponse.ErrorCode, userInfoResponse.ErrorMessage
                );
            }
            var resultUserInfo = _mapper.Map<WeChatMember>(userInfoResponse);
            return resultUserInfo;
        }
        #endregion        

        #region 只插入会员
        /// <summary>
        /// 只插入会员
        /// </summary>
        /// <param name="weChatMemberInfo"></param>
        /// <returns></returns>
        private async Task<bool> InsertPosMemberAsync(WeChatMemberVerAdd weChatMemberInfo)
        {
            var result = false;

            var appId = weChatMemberInfo.appId;
            var openId = weChatMemberInfo.openId;
            var sourceWarehouseID = weChatMemberInfo.sourceWarehouseID;
            var memberName = weChatMemberInfo.memberName;
            var memberTypeID = weChatMemberInfo.memberTypeID;
            var memberTel = weChatMemberInfo.memberTel;
            var memberNo = weChatMemberInfo.memberNo;
            var memberSex = weChatMemberInfo.memberSex;
            var memberBirthday = weChatMemberInfo.memberBirthday;
            //_logger.LogInformation($"会员xg:【openId:{openId},memberTel:{memberTel}】");
            var db = await _posMemberRepository.GetDbContextAsync();
            //根据openId获取会员
            var posMember = await db.Set<PosMember>().AsNoTracking().FirstOrDefaultAsync(x => x.openId == openId);
            //根据手机号获取会员
            var posTelMember = await db.Set<PosMember>().AsNoTracking().FirstOrDefaultAsync(x => memberTel != null && x.memberTel == memberTel);
            //_logger.LogInformation($"会员update:【posTelMember:{UtilsHelper.SerializeObject(posTelMember)},posTelMember:{UtilsHelper.SerializeObject(posTelMember)}】");
            if (posMember == null && posTelMember == null)
            {
                //如果openId和手机号都不存在，则插入一条新记录

                //如果名字空那需要调接口获取昵称
                if (string.IsNullOrEmpty(memberName))
                {
                    //空就赋一个初始值
                    memberName = "新用户";
                    ////获取微信用户详情
                    //var weChatMember = await GetWeChatUserInfoByOpenId(openId, appId);
                    //memberName = string.IsNullOrEmpty(weChatMember.Nickname) ? "新用户" : weChatMember.Nickname;
                }

                posMember = new PosMember()
                {
                    sourceWarehouseID = sourceWarehouseID,
                    startDate = DateTime.Now,
                    endDate = DateTime.Now.AddYears(100),
                    memberName = memberName,
                    memberTel = memberTel,
                    cardAmount = 0,
                    TotalConsAmount = 0,
                    integral = 0,
                    openId = openId,
                    sex = memberSex,
                    memberBirthday = memberBirthday,
                    No = !string.IsNullOrEmpty(memberNo) ? memberNo : !string.IsNullOrEmpty(memberTel) ? memberTel : await _noGeneratorService.GenerateGeneralNoAsync("MB"),
                    memberTypeID = memberTypeID,
                    addTime = DateTime.Now
                };
                //存库
                _entityHelper.InitEntity(posMember);
                await _posMemberRepository.InsertAsync(posMember, autoSave: true);
                result = true;
            }
            else if (posMember == null && posTelMember != null)
            {
                //如果openId不存在，手机号都存在，则更新相应记录的openId
                using var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true);
                try
                {
                    //更新存在的手机号记录的openId
                    posTelMember.openId = openId;
                    //posTelMember.No = !string.IsNullOrEmpty(memberNo) && posTelMember.No == posTelMember.memberTel && posTelMember.No != memberNo ? memberNo : posTelMember.No;
                    posTelMember.No = !string.IsNullOrEmpty(memberNo) && posTelMember.No != memberNo ? memberNo : posTelMember.No;
                    posTelMember.updateTime = DateTime.Now;
                    _logger.LogInformation($"会员更新后信息:【{UtilsHelper.SerializeObject(posTelMember)}】");
                    _entityHelper.SetUpdationInfo(posTelMember);
                    await _posMemberRepository.UpdateAsync(posTelMember);

                    await uow.CompleteAsync();

                    result = true;
                }
                catch (Exception e)
                {
                    await uow.RollbackAsync();
                    _logger.LogError(message: e.Message, exception: e);
                    throw;
                }
            }
            else if(posMember != null && posTelMember == null)
            {
                //如果openId存在，手机号不存在，则更相应记录的手机号
                using var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true);
                try
                {
                    //如果名字不为空那重新赋值会员名
                    if (!string.IsNullOrEmpty(memberName))
                        posMember.memberName = memberName;
                    //更新性别，由于关注时候拿不到性别，这边领卡时候赋值
                    posMember.sex = memberSex;
                    //更新存在的openId的手机号记录
                    posMember.memberTel = memberTel;
                    posMember.memberBirthday = memberBirthday;
                    posMember.No = !string.IsNullOrEmpty(memberNo) ? memberNo : posMember.No;
                    posMember.updateTime = DateTime.Now;
                    _entityHelper.SetUpdationInfo(posMember);
                    await _posMemberRepository.UpdateAsync(posMember);

                    await uow.CompleteAsync();

                    result = true;
                }
                catch (Exception e)
                {
                    await uow.RollbackAsync();
                    _logger.LogError(message: e.Message, exception: e);
                    throw;
                }
            }
            else if (posMember != null && posTelMember != null)
            {
                //如果openId和手机号都存在，则需要判断是否是同一条记录，如果是两条记录需要合并
                if (posMember.Id != posTelMember.Id)
                {
                    //需要合并记录
                    using var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true);
                    try
                    {
                        //更新存在的手机号记录的openId
                        posTelMember.openId = openId;
                        posTelMember.No = !string.IsNullOrEmpty(memberNo) && posTelMember.No == posTelMember.memberTel && posTelMember.No != memberNo ? memberNo : posTelMember.No;
                        posTelMember.updateTime = DateTime.Now;
                        _entityHelper.SetUpdationInfo(posTelMember);
                        await _posMemberRepository.UpdateAsync(posTelMember);
                        //删除openId存在，手机号不存在的记录
                        await _posMemberRepository.DeleteAsync(posMember);

                        await uow.CompleteAsync();

                        result = true;
                    }
                    catch (Exception e)
                    {
                        await uow.RollbackAsync();
                        _logger.LogError(message: e.Message, exception: e);
                        throw;
                    }
                }
            }

            return result;

            ////会员不存在则需要新增                
            //var posMember = new PosMember()
            //{
            //    sourceWarehouseID = sourceWarehouseID,
            //    startDate = DateTime.Now,
            //    endDate = DateTime.Now.AddYears(100),
            //    memberName = memberName,
            //    memberTel = memberTel,
            //    cardAmount = 0,
            //    TotalConsAmount = 0,
            //    integral = 0,
            //    openId = openId,
            //    addTime = DateTime.Now
            //};
            ////添加卡号,原有的不动，新增的会员号存手机号
            //if (!string.IsNullOrEmpty(memberTel))
            //{
            //    posMember.No = memberTel;
            //}
            //else
            //{
            //    posMember.No = await _noGeneratorService.GenerateGeneralNoAsync("MB");
            //}
            //posMember.memberTypeID = memberTypeID;
            ////获取微信用户详情
            //var weChatMember = await GetWeChatUserInfoByOpenId(openId, appId);
            //posMember.memberName = weChatMember.Nickname;
            //_entityHelper.InitEntity(posMember);
            //await _posMemberRepository.InsertAsync(posMember, autoSave: true);

            //return posMember;
        }
        #endregion        

        #endregion
    }
    #endregion
}
